﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Meraz.Core.Model;

namespace Meraz.Core.Parsers
{
    public abstract class RegexBlogParser : BlogParserBase
    {
        public override PostValues Parse(string permalink, string source)
        {
            LinksToIgnoreList = new List<string>();
            LinksToIgnoreList.Add(permalink);
            if (string.IsNullOrWhiteSpace(source))
                return null;
            PostValues post = new PostValues();
            post.Aliases = ParseAliases(source);
            post.BlogName = this.BlogKey.ToString();
            post.Body = CollapseWhitespace(ParseBody(source));
            post.Links = ParseLinks(post.Body);
            post.Permalink = permalink;
            post.Pubdate = ParseDate(source);
            post.Title = GetTitle(source);

            if (post.Links.Count > 0)
            {
                foreach (string linkToRemove in LinksToIgnoreList)
                    post.Links.Remove(linkToRemove);
            }
            CleanUp(post);

            return post;
        }
        internal abstract List<string> ParseAliases(string source);
        internal abstract DateTime ParseDate(string source);
        internal abstract string ParseBody(string source);
        internal virtual void CleanUp(PostValues post)
        {
            //does nothing by default
        }
        internal string RemoveTags(string tagName, string source)
        {
            string tag = tagName.Trim('<', '>');
            int start = source.IndexOf("<" + tag);
            string endTag = string.Format("</{0}>", tag);
            if (start < 0)
            {
                int end = source.IndexOf(endTag);
                if (end < 0)
                    return source;
                else
                {
                    end += endTag.Length;
                    return source.Remove(0, end);
                }
            }
            else
            {
                int end = source.IndexOf(endTag, start);
                if (end < 0)
                    return source.Remove(start);

                end += endTag.Length;
                return source.Remove(start, end - start);
            }
        }

    }
}
